<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 小红帽
 -->

<template>
  <div>
    <van-form class="red-hat">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.phone"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 验证码 -->
      <div class="popup-open__form-code">
        <van-field
          v-model="ruleForm.verify_code"
          type="tel"
          label="验证码"
          placeholder="请填写验证码"
          clearable
        />
        <van-image :src="imageSrc" @click="onGetCaptcha">
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-checkbox-group v-model="type" direction="horizontal">
            <van-checkbox
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.name"
              checked-color="#e4393c"
              shape="square"
            >{{ option.label }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell class="van-cell__tip" v-for="(content, index) in returnContent" :key="index" :title="content" />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.member_name">
        <template #right-icon>
          <van-switch
            v-model="list.is_open"
            active-color="#e4393c"
            size="24"
            @change="onChange(list)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import * as hat from "@/api/red-hat";
export default {
  name: "RedHat",
  props: {
    index: {
      type: String,
      default: '0'
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        phone: "18206488595",
        password: "123456",
        code_key: "",
        verify_code: "",
        phone_type: "i"
      },
      // 图形验证码
      imageSrc: "",
      // 循环时间
      IntervalTime: 15,
      // 任务类型
      type: ["3"],
      typeOptions: [{ label: "不接浏览单", name: "3" }],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      token: "",
      show: false,
      accountList: [],
      taobao_id: "",
      // 已接单标记
      isAcceptSuc: false,
activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 39 && this.index !== '') {
        this.$emit("changeOpened", {
          index: this.index,
          startFlag: this.startFlag,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
            content: this.returnContent
        });
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 39 && this.index !== '') {
        
        if (!this.item.startFlag) {
          this.onGetCaptcha();
        }
        this.activeIndex = this.index;
// 获取保存账号信息
        this.ruleForm.phone = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || ["3"];
        this.startFlag = this.item.startFlag;
        this.returnContent = this.item.content;
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    },
    returnContent() {
      if (this.item.index === 39) {
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    }
  },
  created() {
    if (this.item.index === 39 && this.index !== '') {
      
      if (!this.startFlag) {
        this.onGetCaptcha();
        this.activeIndex = this.index;
// 获取保存账号信息
        this.ruleForm.phone = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || ["3"];
        this.startFlag = this.item.startFlag;
        this.returnContent = this.item.content;
      }
    }
  },
  methods: {
    // 获取验证码
    onGetCaptcha() {
      this.imageSrc = "";
      this.ruleForm.code_key = hat.getCodeKey();
      this.$axios.get(hat.getImg + this.ruleForm.code_key).then(() => {
        this.imageSrc = hat.getImg + this.ruleForm.code_key;
      });
    },
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          data: this.ruleForm
        };
        hat.ajaxFun(hat.getLogin, param, res => {
          _this.returnContent.unshift(alertMsg(res.info));
          if (res.status === 1) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.phone,
              pass: _this.ruleForm.password,
              type: _this.type,
              index: _this.index
            });
            _this.token = res.data.login_token;
            _this.onGetAccountList();
          } else {
            _this.startFlag = false;
            _this.onGetCaptcha();
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.isAcceptSuc = false;
        this.startFlag = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取账号列表
    onGetAccountList() {
      const _this = this;
      let param = {
        type: "post",
        data: {
          token: this.token
        }
      };
      hat.ajaxFun(hat.getAccountList, param, res => {
        if (res.status === 1) {
          // 接单
          _this.accountList = res.data;
          _this.show = true;
        } else {
          _this.startFlag = false;
          _this.onGetCaptcha();
        }
      });
    },
    // 选择接单账号
    onChange(list) {
      const _this = this;
      _this.show = false;
      _this.returnContent.unshift(
        alertMsg("接单号: " + list.member_name + " 即将开始接单，请耐心等待...")
      );
      _this.taobao_id = list.id;
      _this.onGetAskforOrder(_this);
    },
    // 加入队列
    onGetAskforOrder(_this) {
      // 加入队列
      let param = {
        type: "post",
        data: {
          type: 1,
          taobao_id: _this.taobao_id,
          token: _this.token
        }
      };
      hat.ajaxFun(hat.getAskforOrder, param, res => {
        _this.returnContent.unshift(
          alertMsg(res.info || "系统正再分配任务中，请稍后")
        );
        if (res.status === 1) {
          _this.onGetDistribuleOrder(_this);
        } else {
          _this.startFlag = false;
        }
      });
    },
    // 查询接单状态
    onGetDistribuleOrder(_this) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        data: {
          type: 1,
          account_id: _this.taobao_id,
          token: this.token
        }
      };
      hat.ajaxFun(hat.getDistribuleOrder, param, res => {
        if (res.status === 1) {
          if (_this.type.length === 0) {
            _this.onConfirmReceipt(_this, res.data);
          } else {
            _this.returnContent.unshift(alertMsg("不接浏览单，跳过..."));
            // 取消
            _this.onCancelOrder(_this, res.data);
          }
        } else {
          _this.returnContent.unshift(alertMsg(res.info));
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetDistribuleOrder(_this);
            }
          }, 1000 * _this.IntervalTime);
        }
      });
    },
    // 接单
    onConfirmReceipt(_this, data) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        data: {
          tid: data.tid,
          search_id: data.search_id,
          son_id: data.son_id,
          account_id: data.account_id,
          token: this.token
        }
      };
      hat.ajaxFun(hat.confirmReceipt, param, res => {
        if (res.status === 1) {
          _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ['接单成功，请前往做单...']
          })
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetAskforOrder(_this);
            }
          }, 1000 * _this.IntervalTime);
        }
      });
    },
    // 取消任务
    onCancelOrder(_this, data) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        data: {
          son_id: data.son_id,
          token: this.token
        }
      };
      hat.ajaxFun(hat.cancelOrder, param, res => {
        if (res.status === 1) {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetAskforOrder(_this);
            }
          }, 1000 * _this.IntervalTime);
        } else {
          _this.onCancelOrder(_this, data);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>